//
//  LWSegmentBar.swift
//  SmartHousekeeper
//
//  Created by 刘森 on 2020/2/21.
//  Copyright © 2020 LS. All rights reserved.
//

import UIKit
import SnapKit

class LWSegmentBar: UIScrollView {
    
    var normalFontSize: CGFloat = Adapter(16) //正常字体大小
    var selectedFontSize: CGFloat = Adapter(17) //选中字体大小
    var lineViewColor: UIColor = KColorRGBA(58, 130, 232) //底线颜色
    var normalTitleColor: UIColor = KColorRGBA(129, 129, 129)
    var selectedTitleColor: UIColor = KColorRGBA(58, 130, 232) //选中颜色
    let buttonTag = 20000
    private var buttonItems: [UIButton]?
    private lazy var lineView: UIView = {
        let value = UIView()
        value.backgroundColor = lineViewColor
        return value
    }()
    private lazy var lineBackGroundView: UIView = {
        let value = UIView()
        return value
    }()
    private lazy var bottomLine: UIView = {
        let value = UIView()
        value.backgroundColor = KColorRGBA(202, 202, 202)
        return value
    }()
    var titles: [String]? {
        didSet {
            if self.titles != nil {
                initWithControlAndSignal()
            }
        }
    }
    
    //选中下标
    var selectIndex: Int = 0  {
        didSet {
            self.makeLineAnimation(index: self.selectIndex)
            self.touch?(self.selectIndex)
        }
    }
    public var touch:((Int) -> ())?
    
    
    var lineViewCenterX_Constraint: ConstraintMakerEditable?
    var firstSetSelectIndex: Bool = false //第一次是否做动画

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(lineBackGroundView)
        self.addSubview(bottomLine)
        lineBackGroundView.addSubview(lineView)
        self.showsVerticalScrollIndicator = false
        self.showsHorizontalScrollIndicator = false
    }
    
    convenience init(titles: [String]) {
        self.init()
        self.titles = titles
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func buttonStyle() -> UIButton{
        let value = UIButton()
        value.setTitleColor(normalTitleColor, for: .normal)
        value.setTitleColor(selectedTitleColor, for: .selected)
        value.titleLabel?.font = KFont(self.normalFontSize)
        return value
    }
    
    func initWithControlAndSignal() {
        guard let newTitles = titles else {
            return
        }
        buttonItems?.removeAll()
        buttonItems = [UIButton]()
        for (idx, title) in newTitles.enumerated() {
            let button = buttonStyle()
            button.setTitle(title, for: .normal)
            button.tag = idx + buttonTag
            self.addSubview(button)
            buttonItems?.append(button)
            
            button.sce.add(.touchUpInside) { (sender) in
                if sender.tag - self.buttonTag == self.selectIndex {
                    return
                }
                for forButton in self.buttonItems! {
                    if forButton.tag == sender.tag {
                        self.selectIndex = forButton.tag - self.buttonTag
                        forButton.titleLabel?.font = KFontBold(self.selectedFontSize)
                    } else {
                        forButton.isSelected = false
                        forButton.titleLabel?.font = KFont(self.normalFontSize)

                    }
                }
            }
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if self.buttonItems == nil, titles == nil {
            return
        }
        let items = self.buttonItems!
        var lastItem: UIButton? = nil
        for (idx, item) in items.enumerated() {
            let title = titles![idx, true] ?? ""
            let width = title.count * (Int(self.selectedFontSize) + 3) + 24
            item.snp.makeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.width.equalTo(width)
                make.height.equalTo(Adapter(30))
                if lastItem == nil {
                    make.left.equalToSuperview().offset(Adapter(12))
                } else {
                    make.left.equalTo(lastItem!.snp.right)
                }
                if idx == items.count - 1 {
                    make.right.equalToSuperview()
                }
                
            }
            lastItem = item
        }
        self.lineBackGroundView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(20)
            make.top.equalToSuperview().offset(Adapter(51))
        }
        self.bottomLine.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
            make.top.equalToSuperview().offset(Adapter(53))

        }
        
        
        if let width = items.last?.frame.maxX {
            self.contentSize = CGSize(width: width, height: 0)
        }
    }
    
    private func makeLineAnimation(index: Int) {
        guard let button = self.buttonItems?[index, true] else {
            return
        }
        button.isSelected = true
        if !self.firstSetSelectIndex {
            self.firstSetSelectIndex = true
            button.titleLabel?.font = KFontBold(self.selectedFontSize)
            self.lineView.snp.makeConstraints { (make) in
                make.width.equalTo(button)
                make.height.bottom.equalTo(self.lineBackGroundView)
                make.centerX.equalTo(button)
            }
        } else {
            self.lineView.snp.remakeConstraints { (make) in
                make.width.equalTo(button)
                make.height.bottom.equalTo(self.lineBackGroundView)
                make.centerX.equalTo(button)
                
            }
            self.lineView.needsUpdateConstraints()
            self.lineView.updateConstraintsIfNeeded()
            UIView.animate(withDuration: 0.3) {
                self.layoutIfNeeded()
            }
        }
        
    }
    
    
}



